package com.pet.controller.AI.sparkAI;

import com.pet.properties.AiSparkImageProperties;
import com.pet.properties.AiSparkLiteProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import okhttp3.*;

@RestController
@RequestMapping("AI")
@Slf4j
@Component
public class SparkAiWebSocket {

    @Autowired
    private AiSparkImageProperties aiSparkImageProperties ;
    @Autowired
    private AiSparkLiteProperties aiSparkLiteProperties;

    public String getAuthUrl() throws Exception {
        // 创建一个 URL 对象，用于解析和访问指定的主机 URL
        URL url = new URL(aiSparkImageProperties.hostUrl);

        // 创建一个 SimpleDateFormat 对象，用于格式化当前日期和时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        // 设置时区为 GMT
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        // 格式化当前日期和时间
        String date = format.format(new Date());
        // 打印格式化后的日期和时间（仅用于调试）
        System.out.println(format + date);

        // 拼接一个字符串，包含主机、日期和请求行信息，用于计算 HMAC-SHA256 签名
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";

        // 使用 HMAC-SHA256 算法和 API 密钥对请求字符串进行签名
        Mac mac = Mac.getInstance("hmacsha256");
        log.info("mac:{}",mac);
        // 创建一个 SecretKeySpec 对象，用于初始化 HMAC-SHA256 算法
        SecretKeySpec spec = new SecretKeySpec(aiSparkImageProperties.apiKey.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        // 初始化 HMAC-SHA256 算法
        mac.init(spec);
        log.info("mac:{}-spec{}",mac,spec);
        // 计算 HMAC-SHA256 签名
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // 将签名结果转换为 Base64 编码的字符串
        String sha = Base64.getEncoder().encodeToString(hexDigits);

        // 构建一个授权字符串，包含 API 密钥、算法、请求头和签名
        String authorization =
                String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", aiSparkImageProperties.apiKey, "hmac-sha256", "host date request-line", sha);

        // 使用 OkHttp 的 HttpUrl 构建一个完整的 URL，将授权信息、日期和主机作为查询参数附加到 URL 上
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder()
                .addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
                .addQueryParameter("date", date)
                .addQueryParameter("host", url.getHost())
                .build();

        // 打印构建好的 URL（仅用于调试）
        // System.err.println(httpUrl.toString());

        // 返回构建好的 URL
        return httpUrl.toString();
    }

    public String getWebsocketLiteUrl() throws Exception {
        String host = aiSparkLiteProperties.host;
        String apiSecret = aiSparkLiteProperties.apiSecret;
        String apiKey = aiSparkLiteProperties.apiKey;
        String path = aiSparkLiteProperties.path;
        log.info("host:{},apiSecret:{},apiKey:{},path:{}",host,apiSecret,apiKey,path);
        // 1. 生成RFC1123格式时间戳
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(new Date());

        // 2. 构建签名原文
        String signatureBase = String.format("host: %s\ndate: %s\nGET %s HTTP/1.1", host, date, path);

        // 3. HMAC-SHA256签名计算
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        hmacSha256.init(secretKey);
        byte[] signatureBytes = hmacSha256.doFinal(signatureBase.getBytes(StandardCharsets.UTF_8));

        // 4. 生成首次Base64编码
        String signature = Base64.getEncoder().encodeToString(signatureBytes);

        // 5. 构建授权头原文
        String authHeaderBase = String.format("api_key=\"%s\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"%s\"",
                apiKey, signature);

        // 6. 生成最终授权头
        String authorization = Base64.getEncoder().encodeToString(authHeaderBase.getBytes(StandardCharsets.UTF_8));

        // 7. 构建最终URL
        String queryParams = String.format(
                "authorization=%s&date=%s&host=%s",
                URLEncoder.encode(authorization, StandardCharsets.UTF_8),
                URLEncoder.encode(date, StandardCharsets.UTF_8),
                URLEncoder.encode(host, StandardCharsets.UTF_8)
        );

        return String.format("wss://%s%s?%s", host, path, queryParams);
    }
}
